export const parseSRT = (srtContent) => {
  if (!srtContent || typeof srtContent !== 'string') {
    return [];
  }

  const subtitles = [];
  const blocks = srtContent.trim().split(/\n\s*\n/);

  for (const block of blocks) {
    const lines = block.trim().split('\n');
    
    if (lines.length < 3) continue;

    const index = parseInt(lines[0]);
    if (isNaN(index)) continue;

    const timeLine = lines[1];
    const timeMatch = timeLine.match(/(\d{2}):(\d{2}):(\d{2}),(\d{3})\s*-->\s*(\d{2}):(\d{2}):(\d{2}),(\d{3})/);
    
    if (!timeMatch) continue;

    const startTime = parseTimeToSeconds(timeMatch[1], timeMatch[2], timeMatch[3], timeMatch[4]);
    const endTime = parseTimeToSeconds(timeMatch[5], timeMatch[6], timeMatch[7], timeMatch[8]);

    const text = lines.slice(2).join('\n').trim();

    if (text && !isNaN(startTime) && !isNaN(endTime)) {
      subtitles.push({
        index,
        start: startTime,
        end: endTime,
        text: cleanText(text)
      });
    }
  }

  return subtitles.sort((a, b) => a.start - b.start);
};

const parseTimeToSeconds = (hours, minutes, seconds, milliseconds) => {
  const h = parseInt(hours) || 0;
  const m = parseInt(minutes) || 0;
  const s = parseInt(seconds) || 0;
  const ms = parseInt(milliseconds) || 0;
  
  return h * 3600 + m * 60 + s + ms / 1000;
};

const cleanText = (text) => {
  // 移除HTML标签
  let cleaned = text.replace(/<[^>]*>/g, '');
  
  // 移除多余的空白字符
  cleaned = cleaned.replace(/\s+/g, ' ').trim();
  
  return cleaned;
};

export const readFileAsText = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    
    reader.onload = (e) => {
      resolve(e.target.result);
    };
    
    reader.onerror = (e) => {
      reject(new Error('Failed to read file'));
    };
    
    // 尝试多种编码
    try {
      reader.readAsText(file, 'utf-8');
    } catch (error) {
      try {
        reader.readAsText(file, 'gbk');
      } catch (error2) {
        reader.readAsText(file);
      }
    }
  });
};

export const matchAudioWithSubtitle = (audioFiles, subtitleFiles) => {
  const pairs = [];
  
  audioFiles.forEach(audioFile => {
    const audioBaseName = getBaseName(audioFile.name);
    let bestMatch = null;
    let bestScore = 0;
    
    subtitleFiles.forEach(subtitleFile => {
      const subtitleBaseName = getBaseName(subtitleFile.name);
      const score = calculateSimilarity(audioBaseName, subtitleBaseName);
      
      if (score > bestScore) {
        bestMatch = subtitleFile;
        bestScore = score;
      }
    });
    
    pairs.push({
      audio: audioFile,
      subtitle: bestMatch,
      similarity: bestScore
    });
  });
  
  return pairs;
};

const getBaseName = (fileName) => {
  return fileName.toLowerCase()
    .replace(/\.(mp3|wav|m4a|srt)$/, '')
    .replace(/[_\-\s\.]+/g, '');
};

const calculateSimilarity = (str1, str2) => {
  if (!str1 || !str2) return 0;
  
  const longer = str1.length > str2.length ? str1 : str2;
  const shorter = str1.length > str2.length ? str2 : str1;
  
  if (longer.length === 0) return 1.0;
  
  const editDistance = levenshteinDistance(longer, shorter);
  return (longer.length - editDistance) / longer.length;
};

const levenshteinDistance = (str1, str2) => {
  const matrix = [];
  
  for (let i = 0; i <= str2.length; i++) {
    matrix[i] = [i];
  }
  
  for (let j = 0; j <= str1.length; j++) {
    matrix[0][j] = j;
  }
  
  for (let i = 1; i <= str2.length; i++) {
    for (let j = 1; j <= str1.length; j++) {
      if (str2.charAt(i - 1) === str1.charAt(j - 1)) {
        matrix[i][j] = matrix[i - 1][j - 1];
      } else {
        matrix[i][j] = Math.min(
          matrix[i - 1][j - 1] + 1,
          matrix[i][j - 1] + 1,
          matrix[i - 1][j] + 1
        );
      }
    }
  }
  
  return matrix[str2.length][str1.length];
};